<?php

namespace Lib\Queue;

class Queue {

    /**
     * 写入
     *
     * @param array $data
     */
    public static function write($queueKey, $data) {

        $objRedis = \Lib\RedisCache::getRedisInstance();

        $value = json_encode($data);
        $objRedis->lPush($queueKey, $value);
    }


    /**
     * 获取列表
     *
     * @return string
     */
    public static function read($queueKey) {
        $objRedis = \Lib\RedisCache::getRedisInstance();

        try {
            $pong = $objRedis->ping();
            if ($pong != '+PONG') {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }

        $ret = $objRedis->rPop($queueKey);

        return empty($ret) ? array() : $ret;
    }


    /**
     * 队列中消息个数
     *
     * @param string $queueKey 存储key
     * @return int
     */
    public static function count($queueKey) {
        $objRedis = \Lib\RedisCache::getRedisInstance();
        $ret      = $objRedis->lLen($queueKey);

        return $ret;
    }

    /**
     * 发出停止信息
     */
    public static function sendStop($cacheKey) {
        $objRedis = \Lib\RedisCache::getRedisInstance();

        $objRedis->set($cacheKey, 1, 60);

        return true;
    }


    /**
     * 检查停止信息
     */
    public static function checkStop($cacheKey) {
        $objRedis = \Lib\RedisCache::getRedisInstance();

        $ret = $objRedis->get($cacheKey);

        return empty($ret) ? false : true;
    }
}

?>